//import { Util } from './../framework/util';
//import { GameManager } from './gameManager';
import { _decorator, Component, Node, Vec3, Quat, ParticleSystemComponent, math, ITriggerEvent, BoxColliderComponent, Prefab, CCFloat, CCBoolean, Game } from 'cc';
import { poolManager } from '../../../../Framework/Scripts/Managers/poolManager';
import { ResMgr } from '../../../../Framework/Scripts/Managers/ResMgr';
import { CocosUtils } from '../../../../Framework/Scripts/Utils/CocosUtils';
import myUtil from '../../../../Framework/Scripts/Utils/myUtil';




import { GameApp } from '../../GameApp';
import { enemyBase } from '../enemyBase';


//import { ResourceUtil } from '../framework/resourceUtil';
//import { Constant } from '../framework/constant';
//import { Monster } from './monster';
//import { PoolManager } from '../framework/poolManager';
//单只弓箭脚本
const { ccclass, property } = _decorator;
@ccclass('Arrow')
export class Arrow extends Component {

    @property({ displayName: "是否穿透物体" })

    private penetrate: boolean = false;

    // @property({ type: Prefab, displayName: "碰撞动画预制体" })
    // private hitNode: Prefab = null;


    @property({ type: CCFloat, displayName: "伤害" })
    private hitNum: number = 25;

    // @property({ type: CCFloat, displayName: "暴击" })
    // private baoji: number = 25

    // private baojiOld: number = 0
    // private hitOld: number = 0

    private hitName: string = ""
    private arrowName: string = ""

    private hitNodeName: string = ""
    private attackTarget: Node = null!
    public isAutoRotate: boolean = true;//箭是否自动调整角度
    public isArrowLaunch: boolean = false;//箭是否弹射

    private _ndBody: Node = null!;//放弓箭特效的节点
    private _curSpeed: number = 0;//当前速度
    private _targetSpeed: number = 0;//目标速度
    private _oriPos: Vec3 = null!;//初始默认位置
    private _oriEulerAngles: Vec3 = null!//初始默认角度
    private _offsetPos: Vec3 = new Vec3();//和玩家之间的向量差
    private _curWorPos: Vec3 = new Vec3();//当前节点世界坐标
    private _disappearRange: number = 625;//箭节点超过玩家这个范围则隐藏
    private _isLoadEffectOver: boolean = false;//是否已经加载完所有特效
    private _isNeedShowEffect: boolean = false;//是否需要特效
    private _targetWorPos: Vec3 = new Vec3();//箭的下次目标位置
    private _curEulerAngles: Vec3 = new Vec3();//当前角度
    private _oriForward: Vec3 = null!;//初始朝向
    private _curForward: Vec3 = new Vec3();//当前朝向
    private _releaseWorPos: Vec3 = new Vec3();//技能释放位置的世界坐标
    private _offsetPos_1: Vec3 = new Vec3();//向量差
    private _offsetPos_2: Vec3 = new Vec3();//向量差
    private _cross: Vec3 = new Vec3();//两个向量叉乘
    private _colliderCom: BoxColliderComponent = null!;//

    private howHit: Node = null

    private fanwei:number=0
    private fanweispr:number=0
    private oldFanwei:number=25//默认攻击范围起始值


    onLoad() {
     
        // this.hitOld = this.hitNum
        // this.baojiOld = this.baoji

        // this.hitNum = skillWallUtil.hit_algorithm(this.hitNum)
        // this.baoji = skillWallUtil.baoji_algorithm(this.baoji)
        this._colliderCom = this.node.getComponent(BoxColliderComponent) as BoxColliderComponent;

    }
    //判断是否打出暴击
    // private isBaoji(): boolean {

    //     const numR: number = util.getRandomInt(1, 100)
    //    // console.log("numR:", numR, this.baoji);

    //     if (numR < this.baoji) {
    //         return true
    //     } else {
    //         return false
    //     }

    // }

    onEnable() {
        this._colliderCom.on('onTriggerEnter', this._onTriggerEnterCb, this);

    }

    onDisable() {
        //   this._colliderCom.off('onTriggerEnter', this._onTriggerEnterCb, this);
    }

    onDestroy() {
        //this._colliderCom.off('onTriggerEnter', this._onTriggerEnterCb, this); 
    }

    start() {
        // [3]
    }

    /**
    * 初始化 
    */
    public init(howHit: Node, speed: number, releaseWorPos: Vec3, isPreload: boolean = false) {
        this.fanwei=this.oldFanwei
      //  console.log("sssssssssssssssssss",GameApp.Instance.playerData);
        
        const f:number=GameApp.Instance.playerData.config. shecheng.level*5
      //  console.log("射程数据",GameApp.Instance.playerData.config. shecheng.level);
        
        this.fanwei+=f
     //   console.log("我的攻击范围单只"+ this.fanwei);
        this.fanweispr=this.fanwei*this.fanwei
        this.howHit = howHit

        //先计算伤害
        this.hitNum = GameApp.Instance.playerData.gongji


        this.hitName = GameApp.Instance.hitName
        this.arrowName = GameApp.Instance.trailName

        this._releaseWorPos.set(releaseWorPos);

        if (!this._ndBody) {
            this._ndBody = this.node.getChildByName("body") as Node;
        }

        this._isLoadEffectOver = false;
        this._isNeedShowEffect = false;
        this._disappearRange = isPreload ? 5 :this.fanweispr;

        this.isArrowLaunch = false;

        if (!this._oriPos) {
            this._oriPos = this.node.position.clone();
        }

        if (!this._oriEulerAngles) {
            this._oriEulerAngles = this.node.eulerAngles.clone();
        }

        if (!this._oriForward) {
            this._oriForward = this.node.forward.clone();
        }

        this.node.active = false;
        this.node.setPosition(this._oriPos);
        this.node.eulerAngles = this._oriEulerAngles;
        this._curForward.set(this._oriForward);

        this._targetSpeed = speed;
        this._curSpeed = speed * 0.5;



        this.node.active = true;


        if (!this._isLoadEffectOver) {


            if (this.arrowName != "") {
                this._showTrail(this.arrowName);
            } else {
                //  console.log("没有特效");

            }

        }






    }



    private _showTrail(effectName: string) {
        let ndTrail: Node | null = this._ndBody.getChildByName(effectName);
        if (ndTrail) {
            ndTrail.active = true;
            this.node.active = true;
            this._isLoadEffectOver = true;
        } else {
            //没有就加载

            poolManager.instance.getNode(ResMgr.Instance.getAsset("prefab", "arrowEffects/" + effectName), this._ndBody)


            this.node.active = true;
            this._isLoadEffectOver = true;


        }
    }

    /**
     *  回收弓箭组，在weapon/arrow下
     *
     * @memberof Arrow
     */
    public recycleArrowGroup() {
        if (this.node.parent) {
            //      console.log("全部回收了");

            poolManager.instance.putNode(this.node.parent);
        }
    }

    /**
     * 击中目标,隐藏箭
     *
     * @memberof Arrow
     */
    public hideArrow() {
        if (!this.node.parent) {
            return;
        }

        //清除拖尾特效残留
        let arrParticle: ParticleSystemComponent[] = this._ndBody.getComponentsInChildren(ParticleSystemComponent);
        arrParticle.forEach((item: ParticleSystemComponent) => {
            item.simulationSpeed = 1;
            item?.clear();
            item?.stop();
        })

        this.node.active = false;

        //如果弓箭组里所有的箭都隐藏了则回收整个弓箭组
        let isAllArrowHide = this.node.parent?.children.every((ndArrow: Node) => {
            return ndArrow.active === false;
        })

        if (isAllArrowHide) {
            this.recycleArrowGroup();
        }
    }



    private _onTriggerEnterCb(event: ITriggerEvent) {





        let other = event.otherCollider.node;



        let ts: enemyBase = other.getComponent(enemyBase)



        if (!ts.isDie) {
            const hit: Node = poolManager.instance.getNode(ResMgr.Instance.getAsset("prefab", "arrowHit/" + this.hitName), other.parent)
            const pos: Vec3 = other.getWorldPosition()
            hit.setWorldPosition(new Vec3(pos.x, 1, pos.z))
            myUtil.playEffect(hit, false, true, 1, true)
            ts.hit(this.hitNum, this.howHit)
            //  console.log("敌人中箭");
            if (!this.penetrate) {
                //    console.log("回收一只");

                this.hideArrow()
            }



        }








    }

    update(deltaTime: number) {


        //计算向量
        // let deltaPos = this.attackTarget.position.subtract(this.node.position);
        // //归一化
        // let dir = deltaPos.normalize()
        // //缩放方向，以速度进行缩放
        // let distancePos = dir.multiplyScalar(this._targetSpeed);
        // //移动
        // let result = this.node.position.add(distancePos);
        // //设置给当前节点
        // this.node.setPosition(result);

        // if (!this.node.parent || !GameManager.ndPlayer || GameManager.isGameOver || GameManager.isGamePause || (this._isNeedShowEffect && !this._isLoadEffectOver)) {
        //     return;
        // }


        //朝forward方向飞行
        this._curSpeed = CocosUtils.lerp(this._targetSpeed, this._curSpeed, 0.25);
        this._targetWorPos.set(0, 0, -deltaTime * this._curSpeed);
        this.node.translate(this._targetWorPos, Node.NodeSpace.LOCAL);
        this._curWorPos.set(this.node.worldPosition);


        //超过玩家一定范围则隐藏
        Vec3.subtract(this._offsetPos, this._curWorPos, GameApp.Instance.player.worldPosition);
        if (this._offsetPos && this._offsetPos.lengthSqr() >= this._disappearRange) {
            this.hideArrow();
        }
    }
}